#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include "log.hpp"

class Tcpclient
{
public:
    Tcpclient(uint16_t port, string ip) : _serverip(ip), _serverport(port), _sockfd(-1)
    {
    }
    ~Tcpclient() {}
    void initclient()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "socket create error" << std::endl;
            exit(2);
        }
    }
    void run()
    {
        
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            if (connect(_sockfd,(struct sockaddr*)&server,sizeof(server))<0)
            {
                //logmessage(ERROR,_sockfd);
                //exit(ERROR);
                cout<<"connect error"<<endl;
            }
            else{
              cout<<"enter "<<endl;
              while(true)
              {string line;
              getline(cin,line);
              write(_sockfd,line.c_str(),line.size());
           
              char buffer[2048];
              int n=read(_sockfd,buffer,sizeof(buffer)-1);
                   if(n > 0)
                {
                    //目前我们把读到的数据当成字符串, 截止目前
                    buffer[n] = 0;
                    std::cout << "Server回显# " << buffer << std::endl;
                }
                else
                {
                    break;
                }
              cout<<buffer<<endl;


              }
           }
        
    }

private:
    int _sockfd;
    uint16_t _serverport;
    string _serverip;
};